library(htmltools)
APP_URL <- "https://pchen-aitutor.hf.space" # ← your Gradio app URL
USER_ID <- "anonymous_user"
browsable(tagList(
# --- styles (fab, bubble, modal) ---
tags$style(HTML("
#tutor-fab{position:fixed;right:20px;bottom:20px;z-index:99999;padding:12px 14px;border-radius:999px;border:1px solid #ddd;background:#fff;box-shadow:0 8px 24px rgba(0,0,0,.15);cursor:pointer;font-weight:600}
#tutor-fab:hover{background:#f6f8ff}
#tutor-sel-btn{position:absolute;display:none;z-index:100000;padding:6px 10px;font-size:12px;border:1px solid #e5e7eb;border-radius:10px;background:#111827;color:#f9fafb;box-shadow:0 8px 24px rgba(0,0,0,.2);cursor:pointer;user-select:none}
#tutor-modal-overlay{display:none;position:fixed;z-index:99998;inset:0;background:rgba(0,0,0,.35)}
#tutor-modal{position:absolute;top:5%;left:50%;transform:translateX(-50%);width:min(980px,95vw);height:min(720px,90vh);background:#fff;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.25);overflow:hidden}
#tutor-modal-header{display:flex;justify-content:space-between;align-items:center;padding:10px 14px;background:#f5f5f7;border-bottom:1px solid #e5e5ea;font-weight:600}
#tutor-close-btn{cursor:pointer;border:none;background:transparent;font-size:18px}
#tutor-iframe{width:100%;height:calc(100% - 18px);border:0}
")),
# modal + iframe
tags$div(id="tutor-modal-overlay",
tags$div(id="tutor-modal",
tags$div(id="tutor-modal-header","AI Calculus Tutor", tags$button(id="tutor-close-btn","✕")),
tags$iframe(id="tutor-iframe", src="")
)
),
# floating button + selection bubble
tags$button(id="tutor-fab","Ask Tutor"),
tags$button(id="tutor-sel-btn","Ask Tutor"),
# script
tags$script(HTML(sprintf("
(function(){
const APP_URL = '%s';
const USER_ID = '%s';
function sel(){ try { return (window.getSelection?window.getSelection().toString():'').trim(); } catch(e){ return ''; } }
function openInline(q, action){
const p = new URLSearchParams({ user_id: USER_ID, q: q||'', action: action||'prefill' });
const frame = document.getElementById('tutor-iframe');
frame.src = APP_URL + '/?' + p.toString(); // Prefill handled by app from URL
document.getElementById('tutor-modal-overlay').style.display='block';
}
function openTab(q, action){
const p = new URLSearchParams({ user_id: USER_ID, q: q||'', action: action||'prefill' });
window.open(APP_URL + '/?' + p.toString(), 'ai_tutor_tab', 'noopener');
}
// floating button: prefill by default; Alt=send; Ctrl/Cmd=new tab
document.getElementById('tutor-fab').addEventListener('click', function(ev){
const q = sel();
const act = ev.altKey ? 'send' : 'prefill';
if (ev.ctrlKey || ev.metaKey) openTab(q, act); else openInline(q, act);
});
// selection bubble near highlighted text
const b = document.getElementById('tutor-sel-btn');
let last='';
function place(x,y){ b.style.left=(x+10)+'px'; b.style.top=(y+10)+'px'; }
function show(){ b.style.display='block'; } function hide(){ b.style.display='none'; }
document.addEventListener('mouseup', e => setTimeout(() => {
const t = sel(); if (t && t.length>=2 && t.length<=800){ last=t; place(e.pageX,e.pageY); show(); } else hide();
}, 20));
window.addEventListener('scroll', hide, {passive:true}); window.addEventListener('resize', hide);
// bubble click: prefill by default; Alt=send; Ctrl/Cmd=new tab
b.addEventListener('click', function(ev){
if (!last) return;
const act = ev.altKey ? 'send' : 'prefill';
if (ev.ctrlKey || ev.metaKey) openTab(last, act); else openInline(last, act);
hide();
});
// close modal
const overlay = document.getElementById('tutor-modal-overlay');
document.getElementById('tutor-close-btn').addEventListener('click', () => overlay.style.display='none');
overlay.addEventListener('click', e => { if (e.target===overlay) overlay.style.display='none'; });
})();
", APP_URL, USER_ID)))
))By the end of this 90-minute lecture, you will be able to:
R skills:
Mathematics is often called the “universal language” because it provides precise tools for describing patterns, relationships, and changes in our world. Today, we begin our journey into calculus by exploring its fundamental building blocks: numbers, variables, functions, and equations.
Think of this section as learning the alphabet before writing poetry. Just as poets use words to express complex emotions and ideas, mathematicians use functions to express complex relationships and changes.
In the real world, we can observe two apples and three potatoes. However, we cannot observe “2” and “3” themselves. Yet everyone knows what “2” means and what “3” means, despite the fact that we never directly observe these abstract concepts.
This remarkable ability reveals something profound: everyone has the capacity to think abstractly! This is the fundamental capacity that makes mathematics possible. When you recognize that two apples and two bananas share the same “twoness,” you are already thinking like a mathematician. This abstraction (moving from concrete objects to abstract concepts) is the foundation of all mathematical reasoning.
Imagine you’re managing a coffee shop. Every day, you observe patterns: - The number of customers varies throughout the day - Your revenue depends on how many cups you sell
These observations involve numbers (like 50 customers and $300 in revenue) and relationships between quantities. Mathematics gives us tools to work with these relationships precisely.
Definition 1.1 (Numbers as Abstractions): Numbers are mathematical objects that represent quantities, measurements, or positions. They abstract away specific physical properties to focus on quantitative relationships.
Definition 1.2 (Variables): A variable is a symbol (usually a letter) that represents an unknown or changing quantity. Variables serve as placeholders that can take on different values.
Important Relationship: \(\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R} \subset \mathbb{C}\)
This means every natural number is also an integer, every integer is also a rational number, every rational number is also a real number, and every real number is also a complex number. In this unit, we focus on real numbers.
# Create a number line visualization
x <- seq(-5, 5, by = 0.1)
y <- rep(0, length(x))
# Create the plot
plot(x, y, type = "l", lwd = 3, col = "black",
xlim = c(-5, 5), ylim = c(-0.5, 0.5),
xlab = "Real Numbers", ylab = "", yaxt = "n",
main = "The Real Number Line")
# Add tick marks and labels
points(c(-4, -3, -2, -1, 0, 1, 2, 3, 4), rep(0, 9), pch = 19, cex = 1.2)
text(c(-4, -3, -2, -1, 0, 1, 2, 3, 4), rep(-0.2, 9),
labels = c(-4, -3, -2, -1, 0, 1, 2, 3, 4))
# Highlight special numbers
points(pi, 0, pch = 19, col = "red", cex = 1.5)
text(pi, 0.3, "π ≈ 3.14", col = "red", cex = 0.8)
points(-sqrt(2), 0, pch = 19, col = "blue", cex = 1.5)
text(-sqrt(2), 0.3, "-√2 ≈ -1.41", col = "blue", cex = 0.8)
# Add arrows
arrows(-5.5, 0, -5, 0, length = 0.1, lwd = 2)
arrows(5, 0, 5.5, 0, length = 0.1, lwd = 2)The Real Number Line showing different types of numbers
Key Learning Points:
Variables in Action: See how changing the input variables (customers, price) immediately affects the output (revenue)
Relationship: Revenue = customers × price demonstrates a constant relationship, regardless of how the values of the variables change.
Let’s return to our coffee shop example from a mathematical perspective. Suppose you’ve established a fixed price of $3.50 per cup (prices don’t change very often in real businesses, so we treat the price as a parameter). Your daily revenue depends linearly on the number of cups sold:
Revenue Function: R(Q) = 3.50Q
Where: - Q = number of cups sold (independent variable) - R = total
revenue in dollars (dependent variable)
- 3.50 = price per cup (parameter)
This is a linear function because revenue increases at a constant rate with each additional cup sold.
Consider a delivery service with a tiered pricing structure: - Short distances (0-5 km): $10 base fee - Medium distances (5-15 km): $10 + $2 per additional km beyond 5 km - Long distances (15+ km): $10 + $20 + $1.50 per additional km beyond 15 km
Piecewise Function: \[C(d) = \begin{cases} 10 & \text{if } 0 \leq d \leq 5 \\ 10 + 2(d-5) & \text{if } 5 < d \leq 15 \\ 10 + 20 + 1.5(d-15) & \text{if } d > 15 \end{cases}\]
This is a piecewise linear function with different slopes for different distance ranges.
Definition 2.1 (Function): A function is a rule that assigns to each input value exactly one output value. We write \(f(x)=y\), where \(x\) is the input (independent variable) and \(y\) is the output (dependent variable). For example, a real-valued function can be written as \(f: \mathbb{R} \to \mathbb{R}\).
Key Properties:
Domain: The set of all possible input values
Range: The set of all possible output values
Well-defined rule: Each input produces exactly one output
For a real function: \(f: \mathbb R \to \mathbb R\)
Function presentation: Functions can be represented in multiple equivalent ways:
Tabular Representation: Discrete input-output pairs
Graphical Representation: Visual plot of the relationship
Algebraic Representation: Mathematical formula
Computational Representation: Algorithm or code
A weather station records temperature throughout the day. The same data can be presented in multiple ways: - Table: Hour-by-hour temperature readings - Graph: A smooth curve showing temperature changes - Formula: A mathematical equation that predicts temperature - Code: An algorithm that computes temperature values
Each representation reveals different aspects of the relationship and serves different purposes. For example, a table gives exact values at specific times, a graph shows overall patterns and trends, a formula allows calculation of temperature at any time, and code enables efficient computation for large datasets.
# Create a comprehensive example showing all representations
set.seed(123)
# Define a temperature function (simplified model)
temperature_func <- function(hour) {
# Base temperature with daily variation
base_temp <- 20
daily_variation <- 8 * sin(2 * pi * (hour - 6) / 24)
noise <- rnorm(length(hour), 0, 1)
return(base_temp + daily_variation + noise)
}
# Generate data
hours <- 0:23
temps <- temperature_func(hours)
# Create a 2x2 layout
par(mfrow = c(2, 2), mar = c(4, 4, 3, 2))
# 1. Table representation (as a plot)
plot(1, type = "n", xlim = c(0, 10), ylim = c(0, 10),
xlab = "", ylab = "", main = "Tabular Representation", axes = FALSE)
text(5, 9, "Hour | Temperature (°C)", cex = 1.2, font = 2)
for(i in 1:8) {
text(5, 8.5 - i*0.8, paste(hours[i], "|", round(temps[i], 1)), cex = 1)
}
text(5, 1, "... (continues for 24 hours)", cex = 0.9, font = 3)
# 2. Graphical representation
plot(hours, temps, type = "b", pch = 19, col = "blue", lwd = 2,
main = "Graphical Representation",
xlab = "Hour of Day", ylab = "Temperature (°C)")
grid()
# 3. Smooth function overlay
hours_smooth <- seq(0, 23, by = 0.1)
temps_smooth <- 20 + 8 * sin(2 * pi * (hours_smooth - 6) / 24)
plot(hours_smooth, temps_smooth, type = "l", lwd = 3, col = "red",
main = "Algebraic Representation",
xlab = "Hour of Day", ylab = "Temperature (°C)")
text(12, 25, "T(h) = 20 + 8sin(2π(h-6)/24)", cex = 1.1, font = 2)
grid()
# 4. Code representation
plot(1, type = "n", xlim = c(0, 10), ylim = c(0, 10),
xlab = "", ylab = "", main = "Computational Representation", axes = FALSE)
code_lines <- c(
"temperature <- function(hour) {",
" base_temp <- 20",
" variation <- 8 * sin(2*pi*(hour-6)/24)",
" return(base_temp + variation)",
"}"
)
for(i in 1:length(code_lines)) {
text(0.5, 9 - i*1.2, code_lines[i], cex = 0.9, adj = 0, family = "mono")
}Multiple Representations of the Same Function
We will focus on representing real functions as mathematical formulas, computer code, and graphs.
\[y = f(x) = 0.5x+2\] In R, we can
write y <- 0.5*x + 2. This defines a function using
vectorized operations: for each input value in
x, R computes the corresponding output value in
y. Because x can be a vector (a sequence of
values), y will also be a vector of the same length.
To draw a graph of a function, we first choose a domain (an interval of \(x\) values) over which we want to plot it. Here is sample R code for plotting the function \(y = 0.5x + 2\):
Examples of commonly used functions:
Please plot the functions above one by one over the domain \((-4, 8)\) using the R environment above or your local RStudio.
The following graph shows all six common function types over the interval [-4, 8], demonstrating how different functions describe different relationships between dependent and independent variables:
# Create a comprehensive comparison of all function types
x <- seq(-4, 8, by = 0.1)
# Define all function types
linear_func <- 0.5 * x + 2
quadratic_func <- 0.2 * (x - 2)^2 + 1
polynomial_func <- 0.02 * x^3 - 0.1 * x^2 + x + 3
exponential_func <- 2^(0.5 * x)
logarithmic_func <- ifelse(x > 0, 2 * log(x) + 5, NA)
trigonometric_func <- 3 * sin(x) + 5
# Create the plot
plot(x, linear_func, type = "l", lwd = 3, col = "#007bff",
ylim = c(-5, 15), xlim = c(-4, 8),
main = "Comparison of Function Types: Different Relations Between Variables",
xlab = "Independent Variable (x)", ylab = "Dependent Variable f(x)",
cex.main = 1.2, cex.lab = 1.1)
# Add all other functions
lines(x, quadratic_func, lwd = 3, col = "#6f42c1")
lines(x, polynomial_func, lwd = 3, col = "#fd7e14")
lines(x, exponential_func, lwd = 3, col = "#dc3545")
lines(x[x > 0], logarithmic_func[x > 0], lwd = 3, col = "#20c997")
lines(x, trigonometric_func, lwd = 3, col = "#6c757d")
# Add grid for better readability
grid(col = "lightgray", lty = 2)
# Add comprehensive legend
legend("topleft",
legend = c("Linear: f(x) = 0.5x + 2",
"Quadratic: f(x) = 0.2(x-2)² + 1",
"Polynomial: f(x) = 0.02x³ - 0.1x² + x + 3",
"Exponential: f(x) = 2^(0.5x)",
"Logarithmic: f(x) = 2ln(x) + 5",
"Trigonometric: f(x) = 3sin(x) + 5"),
col = c("#007bff", "#6f42c1", "#fd7e14", "#dc3545", "#20c997", "#6c757d"),
lwd = 3, cex = 0.9, bg = "white")
# Add annotations to highlight key differences
text(-2, 12, "Different functions capture\ndifferent types of relationships:",
cex = 1.1, font = 2, adj = 0)
text(-2, 10, "• Linear: Constant rate of change", cex = 0.9, adj = 0)
text(-2, 9.2, "• Quadratic: Accelerating change", cex = 0.9, adj = 0)
text(-2, 8.4, "• Exponential: Explosive growth", cex = 0.9, adj = 0)
text(-2, 7.6, "• Logarithmic: Diminishing growth", cex = 0.9, adj = 0)
text(-2, 6.8, "• Trigonometric: Periodic patterns", cex = 0.9, adj = 0)
text(-2, 6.0, "• Polynomial: Complex curves", cex = 0.9, adj = 0)Comparison of Common Function Types over [-4, 8]
TechStart Inc. is analyzing its growth patterns. The company’s user base grows exponentially: \(U(t) = 1000 \cdot e^{0.2t}\) where \(t\) is time in months.
The marketing team asks: “If we want to reach 5000 users, how many months will it take?”
This question requires finding the inverse of the exponential function, leading us to logarithmic functions.
Additionally, the company’s revenue depends on both user growth and pricing strategy: \(R(t) = P(U(t))\) where \(P(u) = 10u^{0.8}\) is the pricing function. This creates a composite function \(R(t) = P(U(t))\).
Given functions \(f: A \to B\) and \(g: B \to C\), the composite function \((g \circ f): A \to C\) is defined by: \[(g \circ f)(x) = g(f(x))\]
Properties: - Associative: \((h \circ g) \circ f = h \circ (g \circ f)\) - Not commutative: \(g \circ f \neq f \circ g\) (in general)
A function \(f: A \to B\) has an inverse function \(f^{-1}: B \to A\) if: \[f^{-1}(f(x)) = x \text{ for all } x \in A\] \[f(f^{-1}(y)) = y \text{ for all } y \in B\]
Existence condition: \(f\) must be one-to-one (injective) and onto (surjective).
\(Y_{USD} = f(X_{AUD}) = 0.6 X_{AUD}\),
\(Z_{YEN} = g(Y_{USD}) = 150 Y_{USD}\)
\(Z_{YEN} = (g\circ f )(X_{AUD}) = g(f(X_{AUD}))=150*(0.6*X_{AUD}) = 90X_{AUD}\)
Exponential Function: \(f(x) = a^x\) where \(a > 0, a \neq 1\)
Natural exponential: \(e^x\) where \(e \approx 2.71828\)
Properties: \(a^{x+y} = a^x \cdot a^y\), \(a^{xy} = (a^x)^y\)
Logarithmic Function: \(g(x) = \log_a(x)\) where \(a > 0, a \neq 1\)
Natural logarithm: \(\ln(x) = \log_e(x)\)
Inverse relationship: \(a^{\log_a(x)} = x\) and \(\log_a(a^x) = x\)
A function \(y = f(x)\) and its inverse function \(y = f^{-1}(x)\) are symmetric about the 45-degree line \(y=x\).
f <- function(x) exp(x)
f_inv <- function(x) log(x)
# Generate x values
x_vals <- seq(-2, 2, by = 0.1)
y_vals <- f(x_vals)
x_inv_vals <- seq(0.1, exp(2), by = 0.1)
y_inv_vals <- f_inv(x_inv_vals)
# Set up the plot
plot(x_vals, y_vals, type = "l", col = "blue", lwd = 2,
xlim = c(-2, 5), ylim = c(-2, 8),
xlab = "x", ylab = "y",
main = "Function and Its Inverse: Symmetry About y = x")
# Plot the inverse
lines(x_inv_vals, y_inv_vals, col = "red", lwd = 2)
# Plot the 45-degree line y = x
abline(a = 0, b = 1, col = "gray", lty = 2, lwd = 2)For \(f(x) = x^2 + 2\) and \(g(y) = e^y\), we have \((g\circ f)(x) = g(f(x)) = e^{x^2+2}\). In R, we can define and plot the composite function in a similar way.
x <- seq(0, 2,0.1)
y <- x^2 + 2
z <- exp(x^2 + 2)
plot(x, z, type = "l", col = "blue", lwd = 2,
main = "Composite Function",
xlab = "x values", ylab = "exp(x² + 2)")Exponential Growth Models:
Why is the exponential function good for describing a growth process? Let’s say you invest $1000 and it grows at \(r = 5\%\) per year. After \(t\) years, the amount is
\[\text{Amount}(t) = 1000(1+r)^t.\] This is exponential growth because time \(t\) is in the exponent. Now imagine the investment doesn’t grow just once per year, but every second (i.e., it grows continuously). In that case, the model becomes \[\text{Amount}(t) = 1000e^{rt} = 1000e^{0.05t}.\] The plot below compares annual compounding, \(1000(1.05)^t\), with continuous compounding, \(1000e^{0.05t}\).
t <- seq(1,5,0.1)
A_a = 1000*1.05^t
A_e = 1000*exp(0.05*t)
plot(t,A_a,type = "l")
lines(t,A_e,col="red")Compound interest: \(A(t) = P(1 + r)^t\),
Technology adoption: \(N(t) = L/(1 + e^{-k(t-t_0)})\) (logistic)
In early stages, a new technology (like smartphones, electric cars, or social media platforms) can spread quickly:
At first: few users, but growth accelerates.
But eventually: most people who want it already have it.
So growth slows, and adoption levels off.
The logistic function models S-shaped (sigmoid) growth:
\[Adoption(t) = \frac{L}{1+e^{-k(t-t_0)}}\] Where:
\(L\) = maximum possible adoption (often called the carrying capacity)
\(k\) = how fast adoption spreads
\(t_0\) = the “midpoint” (when adoption hits 50%)
Logarithmic Applications:
Time to reach target: \(t = \frac{\ln(N/N_0)}{r}\)
Elasticity of demand: \(\epsilon = \frac{d \ln Q}{d \ln P}\)
Information theory: \(H = -\sum p_i \ln(p_i)\)
Calculate the following without using a computer:
\[\sum_{i=1}^{10} i = 1+2+3+4+5+6+7+8+9+10 = (1+10) + (2+9) + (3+8) + (4+7) + (5+6) = 55.\]
## [1] 55
## [1] 2.49093
Experience the power of R in computing complex summation expressions by modifying and running the R code above in the following R environment.
A business analyst encounters various equation-solving challenges:
A startup company wants to find its break-even point where total revenue equals total cost:
To find the break-even point, set \(R(Q)=C(Q)\): \(25Q = 5000 + 15Q\) \(10Q = 5000\) \(Q = 500\) units
Finding where supply equals demand:
At equilibrium, set \(Q_s = Q_d\): \(-100 + 2P = 300 - P\) \(3P = 400\) \(P = \$133.33\), \(Q = 166.67\) units
These are examples of solving equations to find where functions intersect.
Definition 4.1 (Equation): An equation is a mathematical statement that two expressions are equal. When one side is zero, we call the solutions roots or zeros.
Definition 4.2 (Root/Zero): A root of f(x) = 0 is a value x = r such that f(r) = 0.
Types of Equations and Solution Methods:
Concrete Example: 3x - 9 = 0 - Solution: x = 9/3 = 3 - Graphical interpretation: The line y = 3x - 9 crosses the x-axis (y = 0) at x = 3
Adjust the values of a, b, and c in the interactive graph below to investigate the relationship between the coefficients and the roots of the equation.
Two real solutions: The blue curve intersects the x-axis at two distinct points (two real roots).
One real solution: The curve touches the x-axis at exactly one point (a repeated real root).
No real solutions: The curve lies entirely above or below the x-axis (no real roots).
Quadratic Equation Summary Table
| Case | Discriminant (\(b^2 - 4ac\)) | Nature of Roots | Root Formulas |
|---|---|---|---|
| Two distinct real roots | \(b^2 - 4ac > 0\) | Real and unequal | \(x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}\) |
| One real root (double) | \(b^2 - 4ac = 0\) | Real and equal (repeated) | \(x = -\frac{b}{2a}\) |
| No real roots (complex) | \(b^2 - 4ac < 0\) | Complex conjugates | \(x = \frac{-b \pm i\sqrt{|b^2 - 4ac|}}{2a}\) |
Concrete Example: Fourth-order polynomial with 4 roots - Factored form: y = (x + 2)(x - 1)(x - 3)(x - 5) - Expanded: \(y = x^4 -7x^3+5x^2+31x-30\) - Four roots: x = -2, 1, 3, 5
Concrete Example: \(e^x - 3 = 0\) - Solution: x = ln(3) ≈ 1.099 - Graphical interpretation: The curve \(y = e^x - 3\) crosses the x-axis at \(x = \ln(3)\)
You can input an equation in the box below and click “Update Function”. The intersections between the function curve and the horizontal axis are the roots of the function, and hence the solutions of the equation. You can use the mouse to move the blue point and read off the values of the solutions.
This section provides review and application questions designed to assess understanding at five different levels. Each level builds upon the previous one, fostering deeper comprehension and the ability to apply concepts in increasingly complex situations.
Today we’ve explored the fundamental building blocks of calculus:
Before moving to the next section, reflect on these questions:
In our next section, we’ll dive deeper into functions and their graphs, exploring how to analyze their behavior, find their key features, and use them to solve more complex problems. The foundation we’ve built today will be essential for understanding limits, continuity, and eventually derivatives.
Remember: Mathematics is a language for describing patterns in our world. The more fluent you become in this language, the more clearly you’ll see the hidden structures that govern everything from economics to physics to biology.
End of Section 1 Lecture Notes